package com.lagou.edu.controller;
import com.lagou.edu.model.AuthCode;
import com.lagou.edu.model.CommonResponse;
import com.lagou.edu.service.EmailFeignClient;
import com.lagou.edu.service.IAuthCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Map;

/**
 * 用户控制器
 * @author shenguotao
 */
@RestController
@RequestMapping("/code")
public class CodeController {

    @Autowired
    private IAuthCodeService authCodeService;

    @Autowired
    private EmailFeignClient emailFeignClient;

    @RequestMapping("/create/{email}")
    public CommonResponse create(@PathVariable("email") String email){
        AuthCode authCode = authCodeService.saveAuthCode(email);
        emailFeignClient.sendMail(email,authCode.getCode());
        CommonResponse response = new CommonResponse();
        response.setRestCode("200");
        response.setRestMsg("请求成功");
        return response;
    }

    @RequestMapping("/validate/{email}/{code}")
    public int validate(@PathVariable("email") String email, @PathVariable("code") String code){
        AuthCode search = new AuthCode();
        search.setEmail(email);
        search.setCode(code);
        AuthCode authCode = authCodeService.findListByCondition(search);
        if(authCode == null){
            return 1;
        }else if(!authCode.getExpiretime().after(new Date())){
            return 2;
        }else {
            return 0;
        }
    }

}
